package com.zyz.common.security.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.zyz.common.core.constants.Constants;
import com.zyz.common.core.constants.HttpConstants;
import com.zyz.common.core.utils.JwtUtil;
import com.zyz.common.core.utils.ThreadLocalUtil;
import com.zyz.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头中拿到token
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 对token进行去头部标识符
        if (StringUtils.hasLength(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replace(HttpConstants.PREFIX,"");
        }
        // 存储用户id 和 tokenKey
        ThreadLocalUtil.set(Constants.THREAD_LOCAL_USER_ID,tokenService.getUserId(token,secret));

        String userUUID = tokenService.getUserUUID(token, secret);
        String tokenKey = tokenService.getTokenKey(userUUID);
        ThreadLocalUtil.set(Constants.THREAD_TOKEN_KEY,tokenKey);
        // 调用tokenService延长key时间
        tokenService.extendTokenTime(token,secret);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
